# -*- coding: utf-8 -*-

"""
调试商品页面的评分元素提取
"""

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import time
import re

def test_rating_extraction():
    """
    测试评分元素提取
    """
    print("开始测试评分元素提取...")
    
    try:
        # 配置Chrome选项
        chrome_options = Options()
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-dev-shm-usage")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--window-size=1920,1080")
        chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
        
        # 指定chromedriver路径
        service = Service("/usr/bin/chromedriver")
        
        # 创建WebDriver实例
        print("正在初始化WebDriver...")
        driver = webdriver.Chrome(service=service, options=chrome_options)
        
        # 访问一个商品页面进行测试
        test_url = "https://www.amazon.com/Stanley-Quencher-Flowstate-Tumbler-Stainless/dp/B0DR9PNXX3"
        print(f"正在访问商品页面: {test_url}")
        driver.get(test_url)
        time.sleep(5)  # 等待页面加载
        
        # 检查页面标题
        print(f"页面标题: {driver.title}")
        
        # 尝试定位评分元素
        print("\n=== 评分元素测试 ===")
        rating_selectors = [
            ".a-icon-alt",  # 主要选择器
            "#acrPopover .a-size-base",
            "[data-hook='rating-out-of-text']",
            ".AverageCustomerReviews .a-size-medium",
            ".a-popover-trigger .a-size-base",
            ".averageStarRatingNumerical",
            "[data-hook='average-star-rating']",
            ".a-icon-star ~ .a-size-base",
        ]
        
        for selector in rating_selectors:
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
                print(f"选择器 '{selector}': 找到 {len(elements)} 个元素")
                for i, element in enumerate(elements):
                    text = element.text.strip()
                    attr_value = element.get_attribute("textContent")
                    inner_html = element.get_attribute("innerHTML")
                    print(f"  元素 {i+1}:")
                    print(f"    text: '{text}'")
                    print(f"    textContent: '{attr_value}'")
                    print(f"    innerHTML: '{inner_html[:100]}...'")
                    
                    # 尝试提取评分数字
                    if text or attr_value:
                        full_text = text or attr_value
                        rating_match = re.search(r'(\d+\.?\d*) out of 5 stars?', full_text)
                        if rating_match:
                            print(f"    提取评分: {rating_match.group(1)}")
            except Exception as e:
                print(f"选择器 '{selector}' 出错: {e}")
        
        # 尝试获取评分元素的属性
        print("\n=== 评分元素属性测试 ===")
        try:
                rating_element = driver.find_element(By.CSS_SELECTOR, ".a-icon-alt")
                print("评分元素属性:")
                print(f"  text: '{rating_element.text}'")
                print(f"  textContent: '{rating_element.get_attribute('textContent')}'")
                print(f"  innerHTML: '{rating_element.get_attribute('innerHTML')}'")
                print(f"  outerHTML: '{rating_element.get_attribute('outerHTML')}'")
                print(f"  aria-label: '{rating_element.get_attribute('aria-label')}'")
        except Exception as e:
            print(f"获取评分元素属性出错: {e}")
        
        # 关闭浏览器
        input("按回车键关闭浏览器...")
        driver.quit()
        print("\n测试完成!")
        
    except Exception as e:
        print(f"测试过程中出现错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_rating_extraction()